#!/usr/bin/python3
# -*- coding: utf-8 -*-

import os
import logging
import json
import aiohttp_jinja2
from aiohttp import web
from aioweb import corelib

import db
import main


routes = web.RouteTableDef()
module_name = 'blog'


@routes.get('/blog')
@corelib.template('blog.html')
async def blog_index(request):
    return {}


@routes.get('/blog/item')
async def blog_item(request):
    data = {'path': ''}
    try:
        params = await corelib.parse_param(request)
        id = params.get('id', None)
        session = db.create_session()
        item = session.query(db.Blog).filter(db.Blog.id == id).first()
        data['item'] = item.single_to_dict()
    except BaseException as e:
        logging.error('\n%s' % corelib.printException(e))
        data['item'] = db.Blog()
    return web.json_response({'code': 0, 'msg': data})


@routes.post('/blog/mkdir')
async def blog_mkdir(request):
    data = {'path': ''}
    try:
        params = await corelib.parse_param(request)
        path = params.get('path', '')
        if len(path) > 0:
            dirc = '/'
            name = path[1:]
            if path.rindex('/') > 0:
                dirc, name = path.rsplit('/', 1)
            session = db.create_session()
            blog = session.query(db.Blog).filter_by(
                path=dirc, name=name).first()
            if blog:
                return web.json_response({'code': -1, 'msg': '%s目录下存在同名%s' % (dirc, name)})
            session.add(db.Blog(path=dirc, name=name, content_type='d'))
            session.commit()
        else:
            return web.json_response({'code': -1, 'msg': 'path is null'})
    except BaseException as e:
        logging.error('\n%s' % corelib.printException(e))
        return web.json_response({'code': -1, 'msg': e})
    return web.json_response({'code': 0, 'msg': '新建成功'})


@routes.post('/blog/save')
async def blog_save(request):
    data = {'path': ''}
    try:
        params = await corelib.parse_param(request)
        id = params.get('id', None)
        name = params.get('name', '')
        summary = params.get('summary', '')
        content = params.get('content', '')
        path = params.get('path', '')
        path = '/' if len(path) <= 0 else path
        data['path'] = path
        session = db.create_session()
        if id:
            # edit
            blog = session.query(db.Blog).filter_by(id=id).first()
            if blog:
                if (blog.user_id and blog.user_id != request.__user__['id'] if request.__user__ else None) or not request.__user__['admin'] if request.__user__ else False:
                    return web.json_response({'code': -1, 'msg': '没有修改的权限'})
                blog.summary = summary
                blog.content = content
            else:
                return web.json_response({'code': -1, 'msg': 'blog不存在'})
        else:
            # new
            dirc = path
            session.add(db.Blog(user_id=request.__user__[
                        'id'] if request.__user__ else None, path=path, name=name, summary=summary, content=content, content_type="-"))
        blog = session.query(db.Blog).filter_by(path=path, name=name).first()
        data['id'] = blog.id
        session.commit()
    except BaseException as e:
        logging.error('\n%s' % corelib.printException(e))
        return web.json_response({'code': -1, 'msg': e})
    return web.json_response({'code': 0, 'msg': data})


@routes.post('/blog/delete')
async def blog_delete(request):
    data = {'path': ''}
    try:
        params = await corelib.parse_param(request)
        keys = params.get('keys', [])
        if len(keys) > 0:
            session = db.create_session()
            main.delete('Blog', keys, session)
            session.commit()
    except BaseException as e:
        logging.error('\n%s' % corelib.printException(e))
        return web.json_response({'code': -1, 'msg': e})
    return web.json_response({'code': 0, 'msg': data})


@routes.get('/%s/page' % module_name)
async def blog_page(request):
    data = {'path': ''}
    try:
        params = await corelib.parse_param(request)
        path = params.get('path', '')
        index = int(params.get('index', '1'))
        pagesize = int(params.get('pagesize', '36'))
        session = db.create_session()
        page = await main.load_page('Blog', index, pagesize=pagesize, filter={'path': path})
        users = [item['user_id'] for item in page['items']]
        userMapper = {item.id: item for item in session.query(db.User).filter(
            db.User.id.in_([item['user_id'] for item in page['items']]))}
        for item in page['items']:
            item['author'] = userMapper.get(
                item['user_id'], db.User(name='guest')).name
        data = dict(data, **page)
        data['path'] = path
    except BaseException as e:
        logging.error('\n%s' % corelib.printException(e))
        data['items'] = []
        data['page'] = {'page': {'total': 0,
                                 'pages': 1, 'index': 1, 'size': pagesize}}
    return web.json_response({'code': 0, 'msg': data})


@routes.get('/%s/items' % module_name)
async def blog_items(request):
    data = {'path': '/'}
    try:
        params = await corelib.parse_param(request)
        path = params.get('path', '/')
        session = db.create_session()
        page = await main.load_items('Blog', filter={'path': path})
        users = [item['user_id'] for item in page['items']]
        userMapper = {item.id: item for item in session.query(db.User).filter(
            db.User.id.in_([item['user_id'] for item in page['items']]))}
        for item in page['items']:
            item['author'] = userMapper.get(
                item['user_id'], db.User(name='guest')).name
        data = dict(data, **page)
        data['path'] = path
    except BaseException as e:
        logging.error('\n%s' % corelib.printException(e))
        data['items'] = []
    return web.json_response({'code': 0, 'msg': data})
